package Thread;

import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask> {
    public A1 runnable;
    //为了方便判定,使用了绝对的时间戳
    public long time;
    public MyTask(A1 runnable, long delay) {
        this.runnable =runnable;
        //取当前时刻的时间戳+delay,作为该任务实际执行的时间戳
        this.time =System.currentTimeMillis()+delay;
    }

    @Override
    public int compareTo(MyTask o) {
        //这样的写法表示每次取出的是最小元素
        return (int)(time - o.time);   //解决优先级阻塞队列的优先级问题
    }
}
class MyTimer {
    //创建一个锁对象
    private Object locker =new Object();

    //这个结构,带有优先级的阻塞队列,核心数据结构
    private PriorityBlockingQueue<MyTask> queue =new PriorityBlockingQueue<>();
    //此处的delay形如 3000 这样的数字(多长时间执行该任务)
    public void schedule(A1 runnable,long delay) {
        //根据参数,构造MyTask,插入队列即可
        MyTask myTask =new MyTask(runnable,delay);
        queue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }

    //在这里构造线程,负责执行具体任务了
    public MyTimer() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        synchronized (locker) {
                            //阻塞队列只有阻塞的入队列和阻塞的出队列,没有阻塞的查看首元素
                            MyTask myTask1 = queue.take();  //出队列
                            long curTime = System.currentTimeMillis();  //获取系统时间
                            if (myTask1.time <= curTime) {
                                //时间到了,可以执行任务了
                                myTask1.runnable.run();
                            } else {
                                //时间还没到
                                //把刚才取出的任务重新塞回到队列中
                                queue.put(myTask1);   //入队列

                                locker.wait( myTask1.time-curTime);  //使用wait等待解决忙等问题,避免cpu浪费资源
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            };
        Thread t =new Thread(runnable,"猪猪侠");
        t.start();
    }
}
public class ThreadDemo41 {
    public static void main(String[] args) {
        MyTimer myTimer =new MyTimer();
        myTimer.schedule(new A1() {
            @Override
            public void run() {
                System.out.println("hello4");
            }
        },4000);
        myTimer.schedule(new A1() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);
        myTimer.schedule(new A1() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);
        myTimer.schedule(new A1() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000);
        System.out.println("hell0");
    }
}
